package com.jcfk.system.utils.mail;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.jcfk.common.web.domain.RetResult;
import com.jcfk.system.domain.dto.MailAttachmentDTO;
import com.jcfk.system.domain.dto.MailImageDTO;
import com.jcfk.system.domain.dto.MailInfoDTO;
import com.jcfk.system.domain.po.SysDictionaryItem;
import com.jcfk.system.service.SysDictionaryItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 邮件工具
 *
 * @author 李炳海
 * @date 2021/10/16 17:54
 */
@Component
public class MailHelper {
    @Autowired
    private JavaMailSender javaMailSender;

    private static String regex = "[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";

    @Value("${spring.mail.username}")
    private String username;


    @Autowired
    private SysDictionaryItemService sysDictionaryItemService;

    /**
     * 发送邮件
     *
     * @param mail 邮件
     */
    public void send(MailInfoDTO mail) throws MessagingException {

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();

        // true表示构建一个可以带附件的邮件对象
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);


        // 设置邮件主题
        helper.setSubject(mail.getSubject());

        // 设置邮件发送者，这个跟application.yml中设置的要一致
        helper.setFrom(mail.getFromMail());

        // 设置邮件接收者，可以有多个接收者，中间用逗号隔开，以下类似
        // helper.setTo(mail.getToMails());

        // 设置邮件抄送人，可以有多个抄送人
        // if (StrUtil.isNotEmpty(mail.getCcMails())) {
        //     helper.setCc(mail.getCcMails());
        // }

        // 设置隐秘抄送人，可以有多个
        if (StrUtil.isNotEmpty(mail.getBccMails())) {
            helper.setBcc(mail.getBccMails());
        }

        // 设置邮件发送日期
        helper.setSentDate(new Date());

        // 设置邮件的正文
        helper.setText("这是测试邮件的正文");

        // 图片
        if (mail.getImages() != null && mail.getImages().size() > 0) {
            for (MailImageDTO image : mail.getImages()) {
                helper.addInline(image.getImageName(), new FileSystemResource(new File(image.getImageFile())));
            }
        }

        // 附件
        if (mail.getAttachments() != null && mail.getAttachments().size() > 0) {
            for (MailAttachmentDTO attach : mail.getAttachments()) {
                helper.addAttachment(attach.getAttachmentName(), attach.getAttachmentFile());
            }
        }

        // 发送邮件
        javaMailSender.send(mimeMessage);
    }

    public RetResult<?> sendEmail(MailInfoDTO mailInfoDTO) {
        List<String> errEmails = new ArrayList<>();

        try {
            // 创建Session会话
            Session session = JavaMailUntil.getSession();
            Multipart multipart = new MimeMultipart();

            // 创建附件
            if (mailInfoDTO.getFiles() != null) {
                for (MailAttachmentDTO file : mailInfoDTO.getFiles()) {
                    BodyPart filePart = new MimeBodyPart();
                    filePart.setFileName(file.getAttachmentName());
                    filePart.setContent(file, "application/octet-stream");
                    multipart.addBodyPart(filePart);
                }
            }


            List<Address> readdresses = new ArrayList<>();
            for (String toMail : mailInfoDTO.getToMails()) {
                try {
                    if (toMail.matches(regex)) {
                        readdresses.add(new InternetAddress(toMail));
                    } else {
                        errEmails.add(toMail);
                    }

                } catch (Exception e) {
                    errEmails.add(toMail);
                }
            }

            Address[] recevieaddresses = readdresses.toArray(new Address[0]);
            if (recevieaddresses.length <= 0) {
                return RetResult.fail("消息发送失败");
            }
            // 消息级别赋值
            QueryWrapper<SysDictionaryItem> itemQueryWrapper = new QueryWrapper<>();
            itemQueryWrapper.eq("dictionary_code", "MessageLevel");
            itemQueryWrapper.eq("item_value", mailInfoDTO.getMessageLevel());
            SysDictionaryItem sysDictionaryItem = sysDictionaryItemService.getOne(itemQueryWrapper);

            if (sysDictionaryItem != null) mailInfoDTO.setMessageLevel(sysDictionaryItem.getItemLabel());

            // 创建邮件对象
            MimeMessage message = new MimeMessage(session);
            // 邮件标题
            message.setSubject("[" + mailInfoDTO.getMessageLevel() + "] " + mailInfoDTO.getSubject());
            message.setText(mailInfoDTO.getText());
            message.setFrom(new InternetAddress(username));
            message.addRecipients(MimeMessage.RecipientType.TO, recevieaddresses);

            if (mailInfoDTO.getCcMails() != null && mailInfoDTO.getCcMails().size() > 0) {
                // 抄送人
                List<Address> addresses = new ArrayList<>();
                for (String ccMail : mailInfoDTO.getCcMails()) {
                    if (ccMail.matches(regex)) {
                        addresses.add(new InternetAddress(ccMail));
                    }
                }
                Address[] ccaddresses = addresses.toArray(new Address[0]);
                message.addRecipients(MimeMessage.RecipientType.CC, ccaddresses);
            }

            // 邮件主体
            BodyPart textPart = new MimeBodyPart();
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(mailInfoDTO.getText());
            textPart.setContent(stringBuilder.toString(), "text/html;charset=utf-8");

            multipart.addBodyPart(textPart);
            // 将邮件装入信封
            message.setContent(multipart);

            // 发送
            Transport.send(message);
            return RetResult.ok(errEmails);
        } catch (MessagingException e) {
            System.out.println(e.getNextException());
            return RetResult.fail(e.getNextException().getMessage());
        }

    }
}
